package org.dawfinn.droiditarian;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dawfinn.droiditarian.server.Geohash;
import org.dawfinn.droiditarian.server.Location;
import org.dawfinn.droiditarian.server.ReverseGeocoder;
import org.dawfinn.droiditarian.server.data.DeedLocation;
import org.dawfinn.droiditarian.server.data.PMF;

import com.google.appengine.api.datastore.Blob;

@SuppressWarnings("serial")
public class DeedLocationServlet extends HttpServlet {

	private static final String LNG_PARAM = "lng";
	private static final String LAT_PARAM = "lat";
	private static final String NAME_PARAM = "name";
	private static final int BLOCK_SIZE = 4096;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		ServletInputStream input = req.getInputStream();
		byte[] buffer = new byte[BLOCK_SIZE];
		int n = 0;
		ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
		while ((n = input.read(buffer)) > 0) {
			imageStream.write(buffer, 0, n);
		}
		byte[] imageBytes = imageStream.toByteArray();
		Blob image;
		if (imageBytes.length > 0) {
			image = new Blob(imageBytes);
			Logger.getLogger(getClass().getName()).log(Level.WARNING,
					"Location request contained image");
		} else {
			image = null;
			Logger.getLogger(getClass().getName()).log(Level.WARNING,
					"Location request did not contain image");
		}

		String deedName = req.getParameter(NAME_PARAM);

		float lat = Float.parseFloat(req.getParameter(LAT_PARAM));
		float lng = Float.parseFloat(req.getParameter(LNG_PARAM));

		PersistenceManager pm = PMF.get().getPersistenceManager();
		String geohash = Geohash.getInstance().encode(lat, lng);
		ReverseGeocoder rg = new ReverseGeocoder();
		Location location = rg.getLocation(lat, lng);

		DeedLocation loc = new DeedLocation(deedName, new Date(), image,
				geohash, location.getLocatlity(), location.getAdminArea(),
				location.getCountry());
		Logger.getLogger(getClass().getName()).log(Level.SEVERE,
				location.getLocatlity() + " " + location.getCountry());

		pm.makePersistent(loc);
		pm.close();
	}
}
